package com.study.juc.atomics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-16 22:54
 * @version: 1.0
 * @description: AtomicIntegerFieldUpdater:以一种线程安全的方式操作非线程安全对象的某些字段
 **/
public class AtomicIntegerFieldUpdaterDemo {
    private static int SIZE = 10;
    public static void main(String[] args) throws InterruptedException {
        BankAccount bankAccount = new BankAccount();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 0; i < SIZE; i++) {
            new Thread(()->{
                try {
                    for (int j = 0; j < 1000; j++) {
                        bankAccount.transferMoney(bankAccount);
                        bankAccount.addMoney();
                    }
                }finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() +"\t"+ bankAccount.getMoney());
        System.out.println(Thread.currentThread().getName() +"\t"+ bankAccount.getMoney1());
    }
}

class BankAccount{
    private String bankName = "CCB";//银行
    // 加锁的实现方式
/*    private int money = 0;
    public synchronized void add(){
        money++;
    }*/

    private AtomicInteger money1 = new AtomicInteger(0);
        public volatile int money = 0;//钱数
    AtomicIntegerFieldUpdater<BankAccount> accountAtomicIntegerFieldUpdater =
            AtomicIntegerFieldUpdater.newUpdater(BankAccount.class,"money");
    //不加锁+性能高，局部微创
    public void transferMoney(BankAccount bankAccount)
    {
        accountAtomicIntegerFieldUpdater.incrementAndGet(bankAccount);
    }
    public int getMoney() {
        return money;
    }

    public void addMoney()
    {
        money1.getAndIncrement();
    }

    public int getMoney1()
    {
       return money1.get();
    }
}
